package com.hehao.java_basic.rsa_jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

public class RSASignatureDemo {

    public static void main(String[] args) {
        try {
            // 生成 RSA 密钥对
            KeyPair keyPair = generateRSAKeyPair();

            // 获取公钥和私钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

            // 创建 JWT 签名算法
            Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);

            // 生成 JWT
            String token = JWT.create()
                    .withIssuer("auth0")
                    .withSubject("test")
                    .withAudience("audience")
                    .withIssuedAt(new Date(System.currentTimeMillis()))
                    .withExpiresAt(new Date(System.currentTimeMillis() + 3600 * 1000))
                    .sign(algorithm);

            System.out.println("JWT: " + token);

            // 验证 JWT
            DecodedJWT verifiedToken = JWT.require(algorithm)
                    .withIssuer("auth0")
                    .build()
                    .verify(token);

            System.out.println("JWT is valid: " + verifiedToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }
}
